﻿/*
 * Created by SharpDevelop.
 * User: wwlng1
 * Date: 9/12/2014
 * Time: 06:03 PM
 * 
 */
using System;
using System.Drawing;
using System.Windows.Forms;

using cogs.Services;


namespace cogs
{
	/// <summary>
	/// Description of ApplicationContext.
	/// </summary>
	public class AppContext : ApplicationContext
	{
		private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);		
	
		private NotifyIcon notifyIcon;
		private ContextMenu notificationMenu;
		private MenuItem menuSyncNow;
		private Timer timerSync;
		
		public AppContext()
		{
			InitializeContext();
			Settings.Default.PropertyChanged += HandleSettingChanged;
			
			if(Settings.Default.GoogleCalendarId==null ||Settings.Default.GoogleCalendarId.Equals("")) {
				SettingsWindow settingWin = new SettingsWindow();
				settingWin.ShowDialog();
				settingWin=null;
			}
			
			StartTimer();
			
			// Add GC here for release some memory due to startup			
			GC.Collect();
			
		}
		
		
		#region Initialize Code
		private void InitializeContext()
        {
			InitializeUI();
		}
		
		private void InitializeUI(){
			notifyIcon = new NotifyIcon();
			notificationMenu = new ContextMenu(InitializeMenu());
			notifyIcon.DoubleClick += IconDoubleClick;
			
			var resources = new System.ComponentModel.ComponentResourceManager(typeof(AppContext));
			notifyIcon.Icon = (Icon)resources.GetObject("$this.Icon");
			
			notifyIcon.ContextMenu = notificationMenu;			
			notifyIcon.Visible = true;
			notifyIcon.Text = "Cogs Outlook Google Sync";
		}
		
		private MenuItem[] InitializeMenu()
		{
			menuSyncNow = new MenuItem("Sync Now", menuSyncNowClick);
			
			var menu = new MenuItem[] {
				new MenuItem("Settings...", menuSettingsClick),
				menuSyncNow,
				new MenuItem("View Log", menuViewLogClick),
				new MenuItem("About", menuAboutClick),
				new MenuItem("Exit", menuExitClick)
			};
			return menu;
		}

		#endregion
		
		private void StartTimer(){
			int interval =Settings.Default.SyncInterval;
			if(interval!=0) {
				timerSync = new Timer();
	            timerSync.Interval = Settings.Default.SyncInterval * 60* 1000;
	            timerSync.Tick += new EventHandler(menuSyncNowClick);
	            timerSync.Enabled = true;
	            timerSync.Start();
			}
		}

		private void StopTimer(){
        	if(timerSync!=null) {
	        	timerSync.Stop();
	        	timerSync.Enabled = false;
	        	timerSync.Dispose();
        	}
		}

		private void HandleSettingChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			StopTimer();
			StartTimer();
		}

		private void HandleSyncManagerStatusChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if(e.PropertyName=="StatusMessage") {
				string message = ((SyncManager)sender).StatusMessage;
				if(!string.IsNullOrEmpty(message)) {
					SetNotifyIconText(message);
				}
				else {
					SetNotifyIconText("Cogs' Outlook Google Sync");
				}
			}
		}
		
		private void SetNotifyIconText(string msg){
			string message = msg;
			
			if(message.Length>57) {
				message = message.Substring(0,57) + "...";
			}
			
			notifyIcon.Text = message;
		}

		
		#region Event Handlers
		private void menuSettingsClick(object sender, EventArgs e)
		{
				SettingsWindow settingWin = new SettingsWindow();
				settingWin.ShowDialog();
				settingWin=null;
				GC.Collect();
		}
		
		private async void menuSyncNowClick(object sender, EventArgs e)
		{
			
			if(!menuSyncNow.Enabled)
				return;
			
			menuSyncNow.Enabled = false;
			try {
				if(Settings.Default.GoogleCalendarId==null || Settings.Default.GoogleCalendarId.Equals("")) {
					menuSettingsClick(sender, e);
				}

				SyncManager syncMgr = new SyncManager();
				syncMgr.PropertyChanged += HandleSyncManagerStatusChanged;;
				await syncMgr.SynchronizeAsync();
			}
			finally {
				menuSyncNow.Enabled = true;
			}
			GC.Collect();
		}

		private void menuViewLogClick(object sender, EventArgs e)
		{
			System.Diagnostics.Process.Start(@"cogs.log");
		}
		
		private void menuAboutClick(object sender, EventArgs e)
		{
			MessageBox.Show("COGS' Outlook Google Sync\nBy Warren Ng\nVersion: "+System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
		}
		
		private void menuExitClick(object sender, EventArgs e)
		{
			Application.Exit();
		}
		
		private void IconDoubleClick(object sender, EventArgs e)
		{
			menuSettingsClick(sender, e);
		}
		#endregion
		
		
		/// <summary>
        /// If we are presently showing a form, clean it up.
        /// </summary>
        protected override void ExitThreadCore()
        {

        	StopTimer();
        	
        	notifyIcon.Visible = false;
        	notifyIcon.Dispose();
        	
        	base.ExitThreadCore();
        }
   
		
	}
	
	
}
